//
//  MainController.m
//  OneBox
//
//  Created by dev on 16/1/18.
//  Copyright © 2016年 donglian@eastunion.net. All rights reserved.
//

#import "MainController.h"
#import "SetIPController.h"
#import "MBProgressHUD+MJ.h"
#import "AppDelegate.h"

@interface MainController ()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *mainWebView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardButton;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *settingButton;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *homePage;
- (IBAction)home:(id)sender;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *reloadButton;


- (IBAction)reload:(id)sender;

/* 注入js信息 */
@property (copy, nonatomic)NSString *jsString;
/* 是否注入js信息 */
@property (copy, nonatomic)NSString *isJsString;

@property (copy, nonatomic)NSString *currentUrl;

@end

@implementation MainController


- (BOOL)shouldAutorotate
{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // 1.设置controller的背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 2.webView的请求
    [self webViewRequest];
}
// webView请求url
- (void)webViewRequest
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.IPStr = [defaults objectForKey:@"IP"];
    
    _mainWebView.scrollView.bounces = NO;
    
    _mainWebView.delegate = self;
    
    // 设置URL
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:7080/OneBox/", self.IPStr]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    [_mainWebView loadRequest:request];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *requestString = [[request URL] absoluteString];
    
//    NSLog(@"%@", requestString);
    self.currentUrl = requestString;
    
    // 如果请求到的地址等于以下三个地址时，相应的底部按钮是否可以交互
    if ([requestString isEqualToString:[NSString stringWithFormat:@"http://%@:7080/OneBox/", self.IPStr]] || [requestString isEqualToString:[NSString stringWithFormat:@"http://%@:7080/OneBox/page/logout", self.IPStr]] || [requestString isEqualToString:[NSString stringWithFormat:@"http://%@:7080/OneBox/timeout", self.IPStr]]) {
        self.homePage.enabled = NO;
        self.settingButton.enabled = YES;
    }else{
        self.homePage.enabled = YES;
        self.settingButton.enabled = NO;
    }

    // 注入js信息
    if ([requestString hasPrefix:@"ios:"]) {
        NSString *logString = [[requestString componentsSeparatedByString:@"ios:"] objectAtIndex:1];
        
        NSString *goString = [[[logString componentsSeparatedByString:@","] objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        self.jsString = [[[logString componentsSeparatedByString:@","] objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        self.isJsString = [[[logString componentsSeparatedByString:@","] objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSURL *url = [NSURL URLWithString:goString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [_mainWebView loadRequest:request];
        return NO;
        
    }
    return YES;
}

// webView加载错误信息
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//    NSLog(@"%ld", (long)error.code);
    
    // 如果错误代码是-1001(即该IP不能请求得到数据)
    if ([error code] == -1001){
        
        [MBProgressHUD showError:@"ip地址错误"];
    }
}
// webView加载完成后
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    // 根据webView当前的状态,来判断按钮的状态
    self.backButton.enabled = webView.canGoBack;
    self.forwardButton.enabled = webView.canGoForward;

    if ([self.currentUrl isEqualToString:[NSString stringWithFormat:@"http://%@:7080/OneBox/page/logout", self.IPStr]]) {
        self.backButton.enabled = NO;
    }
    
    if ([self.isJsString isEqualToString:@"y"]) {
        [_mainWebView stringByEvaluatingJavaScriptFromString:self.jsString];
        
        self.isJsString = @"n";
    
    }
}

// 隐藏状态栏
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - 设置
- (IBAction)settingButton:(id)sender {

    UIStoryboard * mainStoryBoard =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SetIPController *sc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"SetIPController"];
    
    [self.navigationController pushViewController:sc animated:YES];
}
#pragma mark - 主页
- (IBAction)home:(id)sender {
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:7080/OneBox/page/main.html", self.IPStr]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [_mainWebView loadRequest:request];
}


#pragma mark - 退出程序
- (IBAction)reload:(id)sender {

    exit(0);

}
@end
